package com.jfs.observer.request.impl;

import com.jfs.enums.SipMethodEnum;
import com.jfs.observer.SIPProcessorObserver;
import com.jfs.observer.request.SIPRequestProcessor;
import com.jfs.observer.request.abstracts.AbstractProcessor;
import com.jfs.properties.SipProperties;
import com.jfs.strategy.register.RegisterStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.sip.RequestEvent;
import javax.sip.SipFactory;
import javax.sip.SipProvider;
import java.util.List;

/**
 * @Description 请求方法为REGISTER类型处理器
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
@Component
@Slf4j
public class SIPRequestRegisterProcessor extends AbstractProcessor implements SIPRequestProcessor, InitializingBean {

    private final SIPProcessorObserver sipProcessorObserver;

    private final List<RegisterStrategy> registerStrategies;

    /**
     * 重写构造
     *
     * @param sipFactory
     * @param tcpSipProvider
     * @param udpSipProvider
     * @param sipProcessorObserver
     * @param sipProperties
     */
    public SIPRequestRegisterProcessor(SipFactory sipFactory,
                                       @Qualifier("tcpSipProvider") SipProvider tcpSipProvider,
                                       @Qualifier("udpSipProvider") SipProvider udpSipProvider,
                                       SIPProcessorObserver sipProcessorObserver,
                                       SipProperties sipProperties,
                                       List<RegisterStrategy> registerStrategies) {
        super(sipFactory, tcpSipProvider, udpSipProvider, sipProperties);
        this.sipProcessorObserver = sipProcessorObserver;
        this.registerStrategies = registerStrategies;
    }

    @Override
    @Async
    public void doProcess(RequestEvent requestEvent) {
        try {
            for (RegisterStrategy registerStrategy : registerStrategies
            ) {
                if (registerStrategy.support(requestEvent)) {
                    registerStrategy.processor(this, requestEvent);
                }
            }
        } catch (Exception e) {
            log.error("处理Register类型请求发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * spring 容器初始化完成 初始化方法
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        sipProcessorObserver.addRequestProcess(SipMethodEnum.REGISTER, this);
    }
}
